package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.credit.pojo.dto.CreditFixedApplyLimitDTO;
import com.xbongbong.pro.credit.pojo.vo.CreditFixedApplyLimitVO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.CreditManagement;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainInLinkItemDTO;
import com.xbongbong.pro.message.constant.CreditLimitPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.DistributorMessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.DistributorAccountEntity;
import com.xbongbong.saas.domain.entity.ext.CreditFixedLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.DistributorCreditStatusEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CreditFixedLimitEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.dictionary.DistributorRoleEnum;
import com.xbongbong.saas.help.DefaultAttrHelp;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.model.CreditFixedLimitModel;
import com.xbongbong.saas.model.CreditLimitModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.service.CreditFixedLimitService;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author xingxing.xiao
 * @date 2020/12/25 11:13
 */
@Service("creditFixedLimitService")
public class CreditFixedLimitServiceImpl implements CreditFixedLimitService {

    private static final Logger LOG = LoggerFactory.getLogger(CreditFixedLimitServiceImpl.class);

    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private DefaultAttrHelp defaultAttrHelp;
    @Resource
    private CreditLimitModel creditLimitModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private CreditFixedLimitModel creditFixedLimitModel;
    @Resource
    private EsHelper esHelper;

    /**
     * 保存前saas特殊校验
     * @param validateDataDTO saas特殊校验数据入参
     * @throws XbbException
     */
    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        Long fixedId = validateDataDTO.getDataId();
        String corpid = validateDataDTO.getCorpid();
        JSONObject data = validateDataDTO.getData();
        // 处理关联客户
        JSONObject customerObj = data.getJSONArray(CreditLimitEnum.CUSTOMER_ID.getAttr()).getJSONObject(0);
        String customerName = customerObj.getString(StringConstant.SAAS_LINK_BUSINESS_NAME);
        saasSaveHelp.formatLinkBusiness4Save(data, CreditFixedLimitEnum.CUSTOMER_ID.getAttr(), CreditFixedLimitEnum.CUSTOMER_NAME.getAttr(), CreditFixedLimitEnum.CUSTOMER_ID.getFieldType());
        boolean isNew = (fixedId == null || Objects.equals(fixedId, 0L));
        if (isNew) {
            // 排除不允许信用额度支付的经销商
            Long customerId = data.getLong(CreditFixedLimitEnum.CUSTOMER_ID.getAttr());
            CustomerEntityExt customerEntityExt = customerModel.getByKey(customerId, corpid);
            if (Objects.nonNull(customerEntityExt)) {
                JSONObject customerData = customerEntityExt.getData();
                String paymentCreditStatus = customerData.getString(DistributorEnum.PAYMENT_BY_CREDIT.getAttr());
                if (Objects.equals(paymentCreditStatus, DistributorCreditStatusEnum.NOT_ALLOW.getCode())) {
                    throw new XbbException(CreditManagement.API_ERROR_253009, String.format(I18nMessageUtil.getMessage(CreditManagement.API_ERROR_253009.getMsg()), customerName));
                }
            }
            // 查询creditId
            if (Objects.isNull(data.getString(CreditFixedLimitEnum.CREDIT_ID.getAttr()))) {
                CreditLimitEntityExt creditLimitEntityExt = creditLimitService.getCreditByCustomerId(customerId, corpid);
                Long creditId = Objects.nonNull(creditLimitEntityExt.getId()) ? creditLimitEntityExt.getId() : 0L;
                data.put(CreditFixedLimitEnum.CREDIT_ID.getAttr(), creditId);
            }
            if (Objects.equals(validateDataDTO.getIsImport(), 1)) {
                // 校验固定额度
                Double oldLimit = data.getDouble(CreditFixedLimitEnum.OLD_LIMIT.getAttr());
                CreditFixedLimitEntityExt latestFixedLimit = getLatestFixedLimit(corpid, customerId);
                JSONObject fixedLimitData = latestFixedLimit.getData();
                if (Objects.nonNull(fixedLimitData)) {
                    Double applyLimit = fixedLimitData.getDouble(CreditFixedLimitEnum.APPLY_LIMIT.getAttr());
                    if (!Objects.equals(applyLimit, oldLimit)) {
                        throw new XbbException(CreditManagement.API_ERROR_253010, String.format(I18nMessageUtil.getMessage(CreditManagement.API_ERROR_253010.getMsg()), CreditFixedLimitEnum.OLD_LIMIT.getAttrName()));
                    }
                }
                data.put(CreditFixedLimitEnum.APPLY_ID.getAttr(), validateDataDTO.getUserId());
                data.put(CreditFixedLimitEnum.APPLY_NAME.getAttr(), validateDataDTO.getLoginUserName());
                data.put(CreditFixedLimitEnum.APPLY_TIME.getAttr(), DateTimeUtil.getTodayInt());
            }
        }
        // 额度不能为负数
        Double applyLimit = data.getDouble(CreditFixedLimitEnum.APPLY_LIMIT.getAttr());
        if (applyLimit < 0) {
            throw new XbbException(CreditManagement.API_ERROR_253008, String.format(I18nMessageUtil.getMessage(CreditManagement.API_ERROR_253008.getMsg()), CreditFixedLimitEnum.APPLY_LIMIT.getAttrName()));
        }
        Double oldLimit = data.getDouble(CreditFixedLimitEnum.OLD_LIMIT.getAttr());
        if (oldLimit < 0) {
            throw new XbbException(CreditManagement.API_ERROR_253008, String.format(I18nMessageUtil.getMessage(CreditManagement.API_ERROR_253008.getMsg()), CreditFixedLimitEnum.OLD_LIMIT.getAttrName()));
        }
    }

    /**
     * 保存后逻辑
     * @param saasFormSaveDTO saas保存数据
     * @throws XbbException
     */
    @Override
    public void afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        String corpid = saasFormSaveDTO.getCorpid();

        // 同步更改信用额度的固定额度字段
        JSONObject newData = saasFormSaveDTO.getNewData();
        String customerId = newData.getString(CreditFixedLimitEnum.CUSTOMER_ID.getAttr());
        BigDecimal applyLimit = newData.getBigDecimal(CreditFixedLimitEnum.APPLY_LIMIT.getAttr());
        CreditLimitEntityExt creditLimitEntity = creditLimitModel.getByCustomerId(customerId, corpid);
        creditLimitEntity.getData().put(CreditLimitEnum.FIXED_LIMIT.getAttr(), applyLimit);
        creditLimitModel.update(creditLimitEntity);

        // 发送消息
        BigDecimal oldLimit = newData.getBigDecimal(CreditFixedLimitEnum.OLD_LIMIT.getAttr());
        Long dataId = creditLimitEntity.getId();
        List<DistributorAccountEntity> distributorAccountEntityList = distributorAccountModel.getAllDistributorUserList(corpid, Long.parseLong(customerId), DistributorRoleEnum.MANAGER.getCode());
        List<String> pushDistributorUserList = distributorAccountEntityList.stream().map(item -> String.valueOf(item.getId())).collect(Collectors.toList());
        PushRefTypePojo.Options options = new PushRefTypePojo.Options(creditLimitEntity.getAppId(), creditLimitEntity.getMenuId(),
                creditLimitEntity.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(),
                XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode(), XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode());
        DistributorMessageRabbitMqDTO distributorMessageRabbitMqDTO = new DistributorMessageRabbitMqDTO(corpid, pushDistributorUserList, Collections.singletonList(dataId), 0, null,
                I18nMessageUtil.getMessage(CreditLimitPushConstant.CREDIT_FIXED_LIMIT_CHANGE_TITLE), String.format(I18nMessageUtil.getMessage(CreditLimitPushConstant.CREDIT_FIXED_LIMIT_CHANGE_CONTENT), oldLimit, applyLimit), null, options, DistributorMarkEnum.DISTRIBUTOR.getCode());
        baseProducer.sendMessage(PushTypeEnum.CREDIT_FIXED_LIMIT_CHANGE_PUSH, distributorMessageRabbitMqDTO);
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result 要返回的jsonobject
     * @throws XbbException 业务异常
     */
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        creditFixedLimitModel.formatData(saasAnalysisDataDTO, result);
    }

    /**
     * 关联新建时格式化解释
     *
     * @param handlerExplainInLinkItemDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatLinkAddExplain(HandlerExplainInLinkItemDTO handlerExplainInLinkItemDTO) throws XbbException {
        JSONObject linkFormData = handlerExplainInLinkItemDTO.getLinkFormData();
        // Long linkDataId = handlerExplainInLinkItemDTO.getLinkDataId(); 此处放的是 customerId, 不使用 linkDataId
        String customerIdStr = linkFormData.getString(CreditFixedLimitEnum.CUSTOMER_ID.getAttr());
        Long customerId = Objects.nonNull(customerIdStr) ? Long.parseLong(customerIdStr) : 0L;
        List<FieldAttrEntity> explainList = handlerExplainInLinkItemDTO.getExplainList();
        FieldAttrEntity linkCustomerField = new FieldAttrEntity();
        for(FieldAttrEntity fieldAttrEntity :explainList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), CreditFixedLimitEnum.CUSTOMER_ID.getAttr())) {
                linkCustomerField = fieldAttrEntity;
            }
        }
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(handlerExplainInLinkItemDTO.getLinkBusinessType());
        switch (redundantTemplateTypeEnum) {
            case CREDIT_LIMIT:
                String customerName = FastJsonHelper.getStringOrDefaultFromFormData(linkFormData, CreditLimitEnum.CUSTOMER_NAME.getAttr(), "");
                linkCustomerField.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(customerId, customerName));
                break;
            default:
                break;
        }
    }

    /**
     * 新建时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        explainList.forEach(item -> {
            if (Objects.equals(item.getAttr(), CreditFixedLimitEnum.APPLY_ID.getAttr())) {
                item.setDefaultAttr(defaultAttrHelp.setUserDefaultAttrPoJo(formatExplainDTO.getUserId(), formatExplainDTO.getLoginUser().getName(),formatExplainDTO.getLoginUser().getAvatar()));
                item.setEditable(0);
            }
            if (Objects.equals(item.getAttr(), CreditFixedLimitEnum.APPLY_TIME.getAttr())) {
                item.setEditable(0);
            }
            if (Objects.equals(item.getAttr(), CreditFixedLimitEnum.OLD_LIMIT.getAttr())) {
                item.setEditable(0);
            }
            if (Objects.equals(item.getAttr(), CreditFixedLimitEnum.CREDIT_FIXED_NO.getAttr())) {
                item.setEditable(0);
            }
        });
    }

    /**
     * 查询最新的固定额度
     * @author xingxing.xiao
     */
    @Override
    public CreditFixedApplyLimitVO getLatestFixedLimit(CreditFixedApplyLimitDTO creditFixedApplyLimitDTO) throws XbbException {
        CreditFixedApplyLimitVO creditFixedApplyLimitVO = new CreditFixedApplyLimitVO();
        Long customerId = creditFixedApplyLimitDTO.getCustomerId();
        String corpid = creditFixedApplyLimitDTO.getCorpid();
        CreditFixedLimitEntityExt latestFixedLimit = getLatestFixedLimit(corpid, customerId);
        JSONObject data = latestFixedLimit.getData();
        double applyLimit = Objects.nonNull(data) ? data.getDoubleValue(CreditFixedLimitEnum.APPLY_LIMIT.getAttr()) : 0D;
        creditFixedApplyLimitVO.setFixedLimit(applyLimit);
        return creditFixedApplyLimitVO;
    }

    /**
     * 格式化导出值
     *
     * @param paasFormDataESList 数据
     * @throws XbbException 异常
     */
    @Override
    public void formatExportValue(List<PaasFormDataEntityExt> paasFormDataESList, FormDataListDTO formDataListDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {

    }

    /**
     * 将Excel数据格式化成表单保存需要的JSON格式的数据
     *
     * @param importFormDataDTO 导入入参
     * @param titlePojoList     标题
     * @param rowGroupPojo      一个表单对应的一组Excel填写的数据
     * @param fieldAttrList     解释
     * @return FormDataAddDTO
     */
    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        formDataAddDTO.setSerialNo("");
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            Integer fieldType = fieldAttr.getFieldType();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttr, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldAttr.getFieldType())) {
                    importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
                } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                    formDataAddDTO.setSerialNo(cellValue.toString());
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                    importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                    importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
                } else {
                    dataJson.put(attr, cellValue);
                }
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    /**
     * 名称一致性同步
     * @param corpid
     * @param customerId
     * @param customerName
     * @return
     * @author xingxing.xiao
     * @date 2021/02/25 16:48
     */
    @Override
    public void dataConsistencyUpdateCustomer(String corpid, Long customerId, String customerName) throws XbbException {
        try {
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid.keyword", corpid))
                    .filter(termQuery("del", 0))
                    .filter(termQuery(CreditFixedLimitEnum.getEsAttr4Keyword(CreditFixedLimitEnum.CUSTOMER_ID), customerId));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CREDIT_FIXED_LIMIT, filter, PaasFormDataEntityExt.class, fieldList);
            Set<Long> ids = new HashSet<>();
            for (PaasFormDataEntityExt esEntity : esEntities) {
                ids.add(esEntity.getDataId());
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", ids);
            param.put("del", 0);
            List<CreditFixedLimitEntityExt> entityList = creditFixedLimitModel.findEntitys(param);
            if (CollectionUtils.isNotEmpty(entityList)) {
                List<UpdateDataEntity> updateList = new ArrayList<>();
                for (CreditFixedLimitEntityExt entity : entityList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(CreditFixedLimitEnum.CUSTOMER_NAME.getAttr(), customerName);
                    UpdateDataEntity updateData = ExplainUtil.getUpdateData(entity.getId(), jsonObject, corpid);
                    updateList.add(updateData);
                }
                creditFixedLimitModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error("CreditFixedLimitServiceImpl.dataConsistencyUpdateCustomer 出错， corpid=" + corpid + " customerId=" + customerId + " customerName=" + customerName, e);
        }
    }

    /**
     * 查询最新的固定额度
     * @param corpid
     * @param customerId
     * @return
     * @author xingxing.xiao
     */
    @Override
    public CreditFixedLimitEntityExt getLatestFixedLimit(String corpid, Long customerId) throws XbbException {
        CreditFixedLimitEntityExt fixedLimitEntityExt = new CreditFixedLimitEntityExt();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String keyword = StringConstant.POINT + StringConstant.KEY_WORD;
        String dataPoint = StringConstant.JSON_DATA + StringConstant.POINT;
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
        boolQueryBuilder.filter(termQuery(dataPoint + CreditLimitEnum.CUSTOMER_ID.getAttr() + keyword, customerId));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.PASS.getType(), FlowStatusEnum.NOT_NEED_APPROVAL.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CREDIT_FIXED_LIMIT.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.sort(new FieldSortBuilder(ParameterConstant.ADD_TIME).order(SortOrder.DESC));
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CREDIT_FIXED_LIMIT.getIndex());
        searchRequest.source(sourceBuilder);
        List<String> fieldList = new ArrayList<>();
        fieldList.add(StringConstant.JSON_DATA);
        List<PaasFormDataEntityExt> dataEntityList = paasEsModel.list(sourceBuilder, IndexTypeEnum.IDX_SAAS_CREDIT_FIXED_LIMIT, fieldList, 1, 1);
        if (!dataEntityList.isEmpty()) {
            PaasFormDataEntityExt dataEntityExt = dataEntityList.get(0);
            BeanUtil.copyProperties(dataEntityExt, fixedLimitEntityExt);
        }
        return fixedLimitEntityExt;
    }

    /**
     * 格式化移动端列表页
     * @param formDataListDTO 用户
     * @param esEntities 业务实体集合
     * @param totalCount 总数
     * @return
     * @throws XbbException
     */
    @Override
    public ListAppVO formatCreditFixedAppList(FormDataListDTO formDataListDTO, List<PaasFormDataEntityExt> esEntities, Integer totalCount) throws XbbException {
        List<AppListPojo> appLists = new ArrayList<>();
        for (PaasFormDataEntityExt entity : esEntities) {
            JSONObject data = entity.getData();
            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();
            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            appLists.add(new AppListPojo(entity.getId(), titleList, summaryList, superScript, lablesList, others, entity.getAppId(), entity.getMenuId(), entity.getFormId()));
        }

        ListAppVO listAppVO = new ListAppVO();
        listAppVO.setList(appLists);
        listAppVO.setTotalCount(totalCount);
        return  listAppVO;
    }
}
